﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
//using MathNet.Numerics.LinearAlgebra;
//using MathNet.Numerics.LinearAlgebra.Double;
//using MathNet.Numerics.Statistics;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class RM692G3 : Form
    {
        // frmMain frmHelp = null;
        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum = new double[25];//目标值-白色
        private byte[] Send_buf = new byte[1];
        List<string> lines;
        private byte[] Rec_tmp = new byte[1];
        private byte[] Rec_tmp1 = new byte[1];
        private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过  
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        //监听NT37701A挂载
        string[] DBV_SET = { "", "" };
        string[] GAMMA_SET = { "", "" };
        public RM692G3()
        {
            InitializeComponent();
        }
        public void ADB_bmp_Traffic(string gray)
        {
            System.Diagnostics.Process p1 = new System.Diagnostics.Process();
            p1.StartInfo.FileName = Application.StartupPath + @"\Resources\adb.exe";
            //是否使用操作系统shell启动
            p1.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            //p1.StartInfo.RedirectStandardInput = true;
            //输出信息
            p1.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p1.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p1.StartInfo.CreateNoWindow = true;
            //应该触发退出事件
            p1.EnableRaisingEvents = true;

            string cmdstr = @"shell  am force-stop com.tools.cit";  //注意最后有一个空格
            p1.StartInfo.Arguments = cmdstr;
            p1.Start();
            p1.WaitForExit(); //等待程序执行完退出进程

            cmdstr = @"shell  am start -n com.tools.cit/.lcd.LCDGrayTest --ei lcdCount " + gray;  //注意最后有一个空格
            p1.StartInfo.Arguments = cmdstr;
            p1.Start();
            p1.WaitForExit(); //等待程序执行完退出进程

            Application.DoEvents();
            p1.Close();
        }

        byte[] gammat = new byte[] {
            //Inter gamma
            0xFE,0x00,
            0x51,0x0d,0xbb,
            0xFE,0x70,
            0x28,0x00,
            0xFE,0x40,
            0xDA,0xC8,
            0xBD,0x00, //60HZ
            0xD7,0x09, //Normal 1
            0xFE,0x78,
            0xF4,0xC0,
            0xF5,0x09,  //Normal 1

            0xFE,0x50,
            //R255 MSB 21   ;LSB 20
            0x20,0x03,
            0x21,0xff,
            //G255
            0x69,0x03,
            0x6A,0xff,
            //B255
            0xAF,0x03,
            0xB0,0xff
        };
        public void ADBbyteArrSend(byte[] cmd)
        {
            System.Diagnostics.Process p1 = new System.Diagnostics.Process();
            p1.StartInfo.FileName = Application.StartupPath + @"\Resources\adb.exe";
            //是否使用操作系统shell启动
            p1.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            //p1.StartInfo.RedirectStandardInput = true;
            //输出信息
            p1.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p1.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p1.StartInfo.CreateNoWindow = true;
            //应该触发退出事件
            p1.EnableRaisingEvents = true;
            //程序退出事件
            p1.Exited += (s, er) =>
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "完成");
            };
            //程序输出消息事件
            p1.OutputDataReceived += (o, er) =>
            {
                if (string.IsNullOrWhiteSpace(er?.Data))
                {
                    return;
                }
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "程序执行消息：" + er.Data);
            };
            string cmdstr = @"root";  //注意最后有一个空格
            p1.StartInfo.Arguments = cmdstr;
            p1.Start();
            //p1.BeginOutputReadLine();
            showmsg("root: " + cmdstr);
            p1.WaitForExit(); //等待程序执行完退出进程
            cmdstr = @"shell echo 0x39 0x01 0x00 0x00 0x00 0x00 ";  //注意最后有一个空格
            cmdstr += cmd.Length + " ";
            for (byte n = 0; n < cmd.Length; n++)
            {
                cmdstr += " " + cmd[n].ToString();
            }
            cmdstr += " " + "" + "  > /d/dri/0/DSI-1/tx_cmd";
            p1.StartInfo.Arguments = cmdstr;
            p1.Start();
            //p1.BeginOutputReadLine();
            //showmsg(cmdstr);
            p1.WaitForExit(); //等待程序执行完退出进程
            Application.DoEvents();
        }
        private void showmsg(string str, params byte[] mesgshowLevel)
        {
            byte MsgshowLevel;
            if (mesgshowLevel != null && mesgshowLevel.Length > 0)
            {
                MsgshowLevel = mesgshowLevel[0];
            }
            else { MsgshowLevel = 0; }
            {
                frmMain.frmain.textBox1.Text += str + "\r\n";
                frmMain.frmain.textBox1.SelectionStart = frmMain.frmain.textBox1.Text.Length;
                frmMain.frmain.textBox1.ScrollToCaret();//滚动到光标处
                if (frmMain.frmain.textBox1.Lines.Length > 3800) frmMain.frmain.textBox1.Clear();
            }
        }

        #region    //---Auto Gamma----------------------
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            string tepGammaR = ""; string tepGammaG = ""; string tepGammaB = "";
            string tepstr = "";
            string RM692G3Gammatxt = "";
            //Int16[] GammaPoint = new Int16[25] { 1, 2, 3, 5, 7, 11, 15, 19, 23, 27, 31, 35, 39, 47, 55, 63, 71, 79, 95, 111, 127, 159, 191, 223, 255 };
            int index = 0;// txt51Dbv.GetFirstCharIndexOfCurrentLine();
            int line = 0;// txt51Dbv.GetLineFromCharIndex(index);
            Int16 gdattmp;
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            //以文本形式保存
                            if (chkGammaFormatForRM692G3.Checked && chkRM692G3dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString(), 10);
                                    tepGammaR += Convert.ToString(gdattmp) + "\r\n";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString(), 10);
                                    tepGammaG += Convert.ToString(gdattmp) + "\r\n";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString(), 10);
                                    tepGammaB += Convert.ToString(gdattmp) + "\r\n";
                                }
                                string str = "";
                                for (int i = 0; i < 25; i++)
                                {
                                    str += Point_RM692G3[i] + "\r\n";
                                }
                                SaveFileDialog txt = new SaveFileDialog();
                                txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                                //string GammaStr = "//-----保存Gamma 寄存器值-----\r\n";
                                if (txt.ShowDialog() == DialogResult.OK)
                                {
                                    if (txt.FileName == " ")
                                    {
                                        return;
                                    }
                                    StreamWriter gsw = null; //文件流
                                    gsw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                                    try
                                    {
                                        tepGammaB = tepGammaB.Substring(0, tepGammaB.Length - 2);
                                        gsw.Write(str + tepGammaR + tepGammaG + tepGammaB);
                                        gsw.Dispose(); //释放资源
                                        gsw.Close(); //关闭数据流
                                        MessageBox.Show("保存Gamma 寄存器保存OK！", "系统提示：");
                                    }
                                    catch
                                    {
                                        MessageBox.Show("保存Gamma 寄存器保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                            else if (chkGammaFormatForRM692G3.Checked && !chkRM692G3dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString());      //变换格式                                    
                                    tepGammaR += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString());
                                    tepGammaG += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString());
                                    tepGammaB += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                }
                                tepstr = "B0," + tepGammaR.Substring(1 - 1, 48 - 1) + "\r\n" + "B1," + tepGammaR.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B2," + tepGammaR.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B3," + tepGammaR.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaR, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B4," + tepGammaG.Substring(1 - 1, 48 - 1) + "\r\n" + "B5," + tepGammaG.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B6," + tepGammaG.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B7," + tepGammaG.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaG, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B8," + tepGammaB.Substring(1 - 1, 48 - 1) + "\r\n" + "B9," + tepGammaB.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "BA," + tepGammaB.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "BB," + tepGammaB.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaB, L-->H : ...\r\n" + tepstr + "\r\n";

                                string str = "";
                                //if (rbt_RM692G3_Gamma9.Checked) { str = "// ---Gamma 9 九--  -\r\n //Gamma set 9--  -\r\n bf,08\r\n"; }
                                //else if (rbt_RM692G3_Gamma10.Checked) { str = "// ---Gamma 10 十---\r\n //Gamma set 10---\r\n bf,09\r\n"; }
                                //else if (rbt_RM692G3_Gamma1.Checked) { str = "// ---Gamma 1 一---\r\n //Gamma set 1---\r\n bf,00\r\n"; }
                                //else if (rbt_RM692G3_Gamma2.Checked) { str = "// ---Gamma 2 二---\r\n //Gamma set 2---\r\n bf,01\r\n"; }
                                //else if (rbt_RM692G3_Gamma3.Checked) { str = "// ---Gamma 3 三---\r\n //Gamma set 3---\r\n bf,02\r\n"; }
                                //else if (rbt_RM692G3_Gamma4.Checked) { str = "// ---Gamma 4 四---\r\n //Gamma set 4---\r\n bf,03\r\n"; }
                                //else if (rbt_RM692G3_Gamma5.Checked) { str = "// ---Gamma 5 五---\r\n //Gamma set 5---\r\n bf,04\r\n"; }
                                //else if (rbt_RM692G3_Gamma6.Checked) { str = "// ---Gamma 6 六---\r\n //Gamma set 6---\r\n bf,05\r\n"; }
                                //else if (rbt_RM692G3_Gamma7.Checked) { str = "// ---Gamma 7 七---\r\n //Gamma set 7---\r\n bf,06\r\n"; }
                                //else if (rbt_RM692G3_Gamma8.Checked) { str = "// ---Gamma 8 八---\r\n //Gamma set 8---\r\n bf,07\r\n"; }
                                //------------------------------------------------------------------------
                                SaveFileDialog txt = new SaveFileDialog();
                                txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                                //string GammaStr = "//-----保存Gamma 寄存器值-----\r\n";
                                if (txt.ShowDialog() == DialogResult.OK)
                                {
                                    if (txt.FileName == " ")
                                    {
                                        return;
                                    }
                                    StreamWriter gsw = null; //文件流
                                    gsw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                                    try
                                    {
                                        //richTextBox_GC_In.Text += str + RM692G3Gammatxt;
                                        gsw.Write(str + RM692G3Gammatxt);
                                        gsw.Dispose(); //释放资源
                                        gsw.Close(); //关闭数据流
                                        MessageBox.Show("保存Gamma 寄存器保存OK！", "系统提示：");
                                    }
                                    catch
                                    {
                                        MessageBox.Show("保存Gamma 寄存器保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                            else if (!chkGammaFormatForRM692G3.Checked && chkRM692G3dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString());      //变换格式
                                    tepGammaR += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString());
                                    tepGammaG += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString());
                                    tepGammaB += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                }

                                tepstr = "B0," + tepGammaR.Substring(1 - 1, 48 - 1) + "\r\n" + "B1," + tepGammaR.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B2," + tepGammaR.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B3," + tepGammaR.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaR, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B4," + tepGammaG.Substring(1 - 1, 48 - 1) + "\r\n" + "B5," + tepGammaG.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B6," + tepGammaG.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B7," + tepGammaG.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaG, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B8," + tepGammaB.Substring(1 - 1, 48 - 1) + "\r\n" + "B9," + tepGammaB.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "BA," + tepGammaB.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "BB," + tepGammaB.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                RM692G3Gammatxt += "//GammaB, L-->H : ...\r\n" + tepstr + "\r\n";
                                //------------------------------------------------------------------------
                                string str = "";

                                frmMain.frmain.textBox1.Text += (str + RM692G3Gammatxt);
                                //richTextBox_GC_In.Text += (str + RM692G3Gammatxt);
                            }
                            else
                            {//保存
                                //SaveFileDialog sf = new SaveFileDialog(); //对话框
                                //sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                //if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    //if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        string fname = Application.StartupPath + @"\l_gamma\RM692G3Gamma" + gammaindex + ".csv";
                                        sw = new StreamWriter(fname, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        //MessageBox.Show("数据保存OK！", "系统提示：");
                                        showmsg("----数据保存OK----");
                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            //OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            //sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            //sf.Title = "数据导入";
                            //if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                string fname = Application.StartupPath + @"\l_gamma\RM692G3Gamma" + gammaindex + ".csv";
                                FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        //index = txt51Dbv.GetFirstCharIndexOfCurrentLine();
                                        //line = txt51Dbv.GetLineFromCharIndex(index);
                                        line = gammaindex;
                                        {
                                            GammaValx[line, i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                            GammaValx[line, i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                            GammaValx[line, i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                            //GammaValue[i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                            //GammaValue[i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                            //GammaValue[i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                        }
                                    }
                                    showmsg("Gamma数据 " + gammaindex + "  导入OK！");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
       
        private double D_x, D_y;
        //private int index = 0;
        private double lum_off, x_off, y_off;
        private double R_x = 0.679;//
        private double R_y = 0.321;
        private double G_x = 0.239;
        private double G_y = 0.717;
        private double B_x = 0.138;
        private double B_y = 0.0479;
        private uint[,] GammaValue = new uint[36, 3];//保存当前Gammavalue
        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y
        private int index = 1;  //AutoGamma 调整顺序
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向        
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        bool STOPAutoGammaFlag = false;     //AutoGamma 停止标志位，解决定时器禁止后AutoGamma无法停止的问题
        UInt32[,] GammaValueTeparr = new UInt32[18 * 3 + 2, 2]; //存放格式化后的GammaValue，以便于直接下发至DDIC
        byte[] ReadBackarr = new byte[32];  //暂存下位机返回数据
        bool GammaReadBackFlag = false; // 下位机返回数据完成标志位
        byte[] GammaValueReceived = new byte[50 * 3]; //存放从下位机接收过来的GammaValue        
        bool ReceivOKFlag = false;
        private int[] Point_RM692G3 = new int[15] {//---Gamma绑点数据
            0,1,3,7,15,23,31,47,63,79,111,143,207,239,255};
        //byte GPN =  (byte) Point_RM692G3.Length; // 获取Gamma绑点数量
        byte GPN = 36; //保存Gamma绑点数量
        private void Msr_CA310()
        {
            frmMain.frmain.Msr_CASDK();
            auto_lum = frmMain.frmain.CASDK_LUM;
            auto_x = frmMain.frmain.CASDK_x;
            auto_y = frmMain.frmain.CASDK_y;
        }   //获取CA310/CA410读数
        private void btnCalGammaValue_Click(object sender, EventArgs e)   //计算对应绑点灰阶值，并连同暂存的Gammavale显示在窗体表格上
        {
            byte tep = (byte)Point_RM692G3.Length;
            D_lum = new double[tep];
            this.GammaReg_dataGridView.Rows.Clear();
            for (byte i = 0; i < tep; i++)
            {
                D_lum[i] = (Math.Pow((Point_RM692G3[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                //txttip.Text += "Gamma Node" + i + ": " + Point_RM692G3[i] + "\r\n";
            }
        }
        private void GammaValueFormat_Click(object sender, EventArgs e)   //GammaValue 值拆分成 Byte 并与实际地址进行转换 以便于后续处理发送至下位机
        {
            uint addr, para1, para2, para3, addr_S, r, g, b, r1, g1, b1;
        }

        private void btnEditDBVsetting_Click(object sender, EventArgs e)
        {
            if (btnEditDBVsetting.Tag != null)
            {//编辑结束
                btnEditDBVsetting.Tag = null;
                btnGroupGammaTune.Enabled = true;
                txt51Dbv.Enabled = false;
                btnEditDBVsetting.Text = "DBV编辑";
                txt51Dbv_TextChanged(null, null);
            }
            else
            {
                btnEditDBVsetting.Tag = "editing";
                btnGroupGammaTune.Enabled = false;
                txt51Dbv.Enabled = true;
                btnEditDBVsetting.Text = "保存锁定";
            }
        }
        private byte[] gamma_r = new byte[30]
           {
                0x14,0x15,0x1a,0x1b,0x20,0x21,0x26,0x27,0x2d,0x2f,0x34,0x35,0x3a,0x3b,0x42,0x43,0x48,0x49,0x4e,0x4f,0x54,0x55,0x5b,0x5c,0x61,0x62,0x67,0x68,0x6d,0x6e,
           };
        private byte[] gamma_g = new byte[30]
        {
                0x16,0x17,0x1c,0x1d,0x22,0x23,0x28,0x29,0x30,0x31,0x36,0x37,0x3d,0x3f,0x44,0x45,0x4a,0x4b,0x50,0x51,0x56,0x58,0x5d,0x5e,0x63,0x64,0x69,0x6a,0x6f,0x70,
        };
        private byte[] gamma_b = new byte[30]
        {
                0x18,0x19,0x1e,0x1f,0x24,0x25,0x2a,0x2b,0x32,0x33,0x38,0x39,0x40,0x41,0x46,0x47,0x4c,0x4d,0x52,0x53,0x59,0x5a,0x5f,0x60,0x65,0x66,0x6b,0x6c,0x71,0x72
        };
        private void GammaValueSet(byte index)  //
        {
            byte[] Gamma_R_MSB = new byte[2] { gamma_r[(GPN - index + 1) * 2 - 2], (byte)(((int)(GammaValue[GPN - index, 0]) >> 8) & 0x0F) };
            byte[] Gamma_R_LSB = new byte[2] { gamma_r[(GPN - index + 1) * 2 - 1], (byte)((int)(GammaValue[GPN - index, 0]) & 0xff) };

            byte[] Gamma_G_MSB = new byte[2] { gamma_g[(GPN - index + 1) * 2 - 2], (byte)(((int)(GammaValue[GPN - index, 1]) >> 8) & 0x0F) };
            byte[] Gamma_G_LSB = new byte[2] { gamma_g[(GPN - index + 1) * 2 - 1], (byte)((int)(GammaValue[GPN - index, 1]) & 0xff) };

            byte[] Gamma_B_MSB = new byte[2] { gamma_b[(GPN - index + 1) * 2 - 2], (byte)(((int)(GammaValue[GPN - index, 2]) >> 8) & 0x0F) };
            byte[] Gamma_B_LSB = new byte[2] { gamma_b[(GPN - index + 1) * 2 - 1], (byte)((int)(GammaValue[GPN - index, 2]) & 0xff) };

            byte Gamma_Page = (byte)Convert.ToInt32("50", 16); //16进制字符串转数字
            byte[] TepArr;
            try
            {
                TepArr = new byte[] {
                    2,0xFE,Gamma_Page,
                    2,Gamma_R_MSB[0],Gamma_R_MSB[1],
                    2,Gamma_R_LSB[0],Gamma_R_LSB[1],
                    2,Gamma_G_MSB[0],Gamma_G_MSB[1],
                    2,Gamma_G_LSB[0],Gamma_G_LSB[1],
                    2,Gamma_B_MSB[0],Gamma_B_MSB[1],
                    2,Gamma_B_LSB[0],Gamma_B_LSB[1],
                    2,0xfe,0x40,
                    2,0xe3,(byte)Convert.ToInt32(GammaBandSelect.Text, 16)
                //4, 0XFF, 0XFF, 0XFF, 15  //添加此延时会导致代码下发失败，原因未知
            };  //byte[] TepArr;
                //TepArr[11] = (byte)GammaBand.Value; //设定对应Gamma序号
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾  
                //-----------------  Application.DoEvents();
                //Thread.Sleep(50);
                //Application.DoEvents();
                //GammaReadBackFlag = true;
                //frmTop.GeneralRegRead(0xb0, 16);
                //Application.DoEvents();
                //Thread.Sleep(60);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }
        private void btnAutoGammaJumpTest_Click(object sender, EventArgs e)
        {
            JumpGammaAdjustFlag = true;
        }
        bool JumpGammaAdjustFlag = false;  //跳过某个绑点标志位，通常用于末尾低灰阶
        UInt32 timeout = 0;
        private void GammavalueCal(int index)
        {// GammaValue = new uint[36, 3];//保存当前Gammavalue
            GammaValue[0, 1] = 0;
            //double[] x = new double[] { 610, 748, 865, 965, 1049, 1127, 1199, 1266, 1381, 1547, 1675, 1785, 1967, 2007 };
            //double[] y = new double[] { 675, 844 ,977, 1087, 1176, 1251, 1316, 1373, 1472, 1632, 1763, 1877, 2066, 2109 };
            double[] x = new double[16];
            double[] y = new double[16];

            //double[] y = new double[] { 675, 844, 977, 1087, 1176, 1251, 1316, 1373, 1472, 1632, 1763, 1877, 2066, 2109 };
            //double[] res = MathNet.Numerics.Fit.Polynomial(x, y, 2);
            //double r = Correlation.Pearson(x, y);//             
            //for (byte i=0;i<13;i++)
            //{
            //    double yy = res[0] + res[1] * x[i] + res[2] * (Math.Pow(x[i], 2.0));
            //}
            ////----------------------
            //double[] x1 = new double[] { 1785, 1967, 2007 };
            //double[] y1 = new double[] {  1877,2066, 2109 };
            //double[] res1 = MathNet.Numerics.Fit.Polynomial(x1, y1, 2);
            //double r1 = Correlation.Pearson(x1, y1);// 

            //for (byte i = 0; i < 2; i++)
            //{
            //    double tep = 1675;                
            //    double yy1 = res[0] + res[1] * tep + res[2] * (Math.Pow(tep, 2.0));

            //}

        }
        private void btnAutoGammas_Click(object sender, EventArgs e)
        {
            if (frmMain.frmain.btnCal_manual.Tag.ToString() != "0calDone")
            {
                frmMain.frmain.btnCal_manual.Enabled = true;
                MessageBox.Show("需要提前连接410并校准~", "提示：");
                return;
            }
            //txtGammaNode_TextChanged(null, null);
            int flag = 1;
            JumpGammaAdjustFlag = false;
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            STOPAutoGammaFlag = false;
            GPN = (byte)Point_RM692G3.Length; // 获取Gamma绑点数量
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[GPN, 3];
            D_lum = new double[GPN];
            index = 1;  //Gamma绑点序号，第一个绑点通常对应255灰阶
            flag1 = flag2 = flag3 = 1;
            numStep_ValueChanged(null, null);   //设定AutoGamma调节步长
            frmMain.frmain.textBox1.Text += "GammaValue最大值被限定为: " + GammaValueMax + "\r\n";
            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < GPN; i++)  //计算相应绑点对应的亮度值
            {
                D_lum[i] = (Math.Pow((Point_RM692G3[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);  //获取调节目标色坐标 x
            D_y = Convert.ToDouble(txtVT_y.Text); ////获取调节目标色坐标 y
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < GPN; i++)   // 通过色坐标已经亮度计算各绑点R/G/B分量对应的亮度值
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("f4"); ;   //显示当前绑点对应的目标亮度值
            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);   //获取色坐标允差范围
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        frmMain.frmain.numPatternR.Value = Point_RM692G3[GPN - index];     //设定绑点灰阶
                                                                                           //numPatternG.Value = Point_RM692G3[GPN - index];
                                                                                           //numPatternB.Value = Point_RM692G3[GPN - index];
                        frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, e);       //显示255白画面，从255白画面开始调节
                        //ADB_Gray_Num_ValueChanged(null,null);
                        Thread.Sleep(200);
                        Msr_CA310();
                        Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                        ReceivOKFlag = false;
                        T17.Enabled = true;   //通过T17定时器进行Gamma调整
                        timeout = 0;
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
            GammaTuning();
        }
        private void GammaTuning()   //AutoGamma处理过程
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 20;  //不能过短，要给显示画面一个稳定的时间
            while (index <= GPN)
            {
                Thread.Sleep(20);
                Msr_CA310();
                lablvshow.Text = "Lv: " + auto_lum.ToString("f4").Substring(0, 6) + "\r\n" + "x: " + auto_x.ToString("f4") + "\r\n" + "y: " + auto_y.ToString("f4") + "\r\n";
                labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("#0.0000");  // 在UI上显示当前绑点的目标亮度值            
                showmsg("Adjust inex:" + GPN + "----" + index + "");
                lum_off = (D_lum[GPN - index] * Convert.ToDouble(numVT_loff.Value) / 1000);  //计算当前绑点允许的亮度误差范围
                x_off = Convert.ToDouble(txtVT_xoff.Text);
                y_off = Convert.ToDouble(txtVT_yoff.Text);       //获取色坐标允许误差范围

                if (index > 10)  //根据灰阶范围修正色坐标误差范围
                {   //根据灰阶范围修正色坐标误差范围
                    if (D_lum[GPN - 1] < 10)
                    {
                        x_off += x_off * 2;
                        y_off += y_off * 2;
                    }
                    else if (D_lum[GPN - 1] < 30)
                    {
                        {
                            x_off += x_off * 2;
                            y_off += y_off * 1;
                        }
                    }
                    else if (D_lum[GPN - 1] < 90)
                    {
                        {
                            x_off += x_off * 1;
                            y_off += y_off * 1;
                        }
                    }
                    else
                    {
                        {
                            //x_off += x_off;
                            //y_off += y_off;
                        }
                    }
                } //根据灰阶范围修正色坐标误差范围
                if (auto_x < 0)
                { auto_x = 0; showmsg("TMD410数据又出错了"); }
                if (auto_y < 0)
                { auto_y = 0; showmsg("TMD410数据又出错了"); }

                if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                    flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                    flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                    flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((flag1 == 0 && flag2 == 0 && flag3 == 0) && (index < 12)) //低灰阶本来就很难调就不这么折腾了
                {   //初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                    Thread.Sleep(10); Msr_CA310(); Thread.Sleep(10); Msr_CA310(); 
                    Msr_CA310();
                    if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                        flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag1 = 1;
                    if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                        flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag2 = 1;
                    if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                        flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag3 = 1;
                }//初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
                Lb_t = 1.0;
                Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
                lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
                lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
                lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);
                if ((lumr < 0))
                {
                    //lumr = 0;
                }
                if ((lumg < 0))
                {
                    //lumg = 0;
                }
                if ((lumb < 0))
                {
                    // lumb = 0;
                }
                if (((flag1 == 0 && flag2 == 0 && flag3 == 0) || JumpGammaAdjustFlag) || (timeout > 3 * numTurnGammaTimeout.Value))
                {
                    if (timeout > 3 * numTurnGammaTimeout.Value)
                    {
                        showmsg("\r\n....----模糊处理---模糊处理----....");
                    }
                    timeout = 0;
                    index++;
                    if (index == GPN)   //  最后一个绑点通常为0，不用调试结束即可
                    {
                        //TimTest.Stop();//停止计时
                        GammatuningOKFlag = true;
                        showmsg("··················调试完成··················");
                        STOPAutoGammaFlag = true;
                        btn_RM692G3_Stop.PerformClick();
                        return;
                    }
                    if (index < GPN)
                    {
                        showmsg(index + "完成...\r\n");
                        for (int i = 0; i < 25; i++)    //本意用于显示当前绑点目标信息，但一般用不到
                        {
                            //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_Hi3288[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";

                            //this.GammaReg_dataGridView.Rows.Clear();
                            //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_Hi3288[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                        }
                        //Thread.Sleep(10); //1秒=1000毫秒，
                        //T17.Enabled = true;
                        flag1 = 1;  //复位 亮度色坐标符合目标标志位
                        flag2 = 1;
                        flag3 = 1;
                        JumpGammaAdjustFlag = false;
                    }
                    rstep = (byte)(int.Parse(numStep.Value.ToString())); ;    //重新获取调节步长
                    gstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    bstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    frmMain.frmain.numPatternR.Value = Point_RM692G3[GPN - index];     //设定绑点灰阶
                                                                                       //numPatternG.Value = Point_RM692G3[GPN - index];
                                                                                       //numPatternB.Value = Point_RM692G3[GPN - index];
                    frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);       //显示255白画面，从255白画面开始调节
                    //ReceivOKFlag = false;
                    Thread.Sleep(10);
                    Msr_CA310(); Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                    //--------------------------
                    GammavalueCal(index);
                    //--------------------------
                    if (!STOPAutoGammaFlag)
                        T17.Enabled = true;
                }
                else
                {
                    if (timeout > numTurnGammaTimeout.Value)
                    {
                        //frmMain.frmain.numPatternR.Value = Point_RM692G3[GPN - index];     //设定绑点灰阶
                        //                                                                   //numPatternG.Value = Point_RM692G3[GPN - index];
                        //                                                                   //numPatternB.Value = Point_RM692G3[GPN - index];
                        //frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);       //显示255白画面，从255白画面开始调节
                        //Thread.Sleep(100);
                        //timeout = 0;
                    }
                    if ((GPN - index == 1) | (GPN - index == 2))//这里index最大值为绑点数量-1；倒数第2个绑点 以及倒数第3个绑点可以做技术处理
                    {
                        //GammaValue[0, 1] = 0;  GammaValue[0, 2] = 0;GammaValue[0, 0] = 0;     //0绑点不调，直接送零
                        GammaValue[GPN - index, 0] = (uint)(GammaValue[GPN - index + 1, 0] * 1.5 * (Point_RM692G3[GPN - index]) / (Point_RM692G3[GPN - index + 1]));  //绑点不调，直接赋值算了，如果有过度不均再手动修正即可
                        GammaValue[GPN - index, 1] = (uint)(GammaValue[GPN - index + 1, 1] * 1.5 * (Point_RM692G3[GPN - index]) / (Point_RM692G3[GPN - index + 1]));
                        GammaValue[GPN - index, 2] = (uint)(GammaValue[GPN - index + 1, 2] * 1.5 * (Point_RM692G3[GPN - index]) / (Point_RM692G3[GPN - index + 1]));
                        {   //写入Gamma，一共两处都要适配
                            CheckandCorrectGammaValue();
                            //GammaValueFormat_Click(null, null);
                            //显示当前(待)写入的Gamma寄存器值
                            txtGammaValue.Text = GammaValue[GPN - index, 0] + "\r\n" + GammaValue[GPN - index, 1] + "\r\n" + GammaValue[GPN - index, 2] + "\r\n";
                            GammaValueSet((byte)index);
                            //Thread.Sleep(20);
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死        
                        }
                        JumpGammaAdjustFlag = true;
                    }
                    //else if (GPN - index == 2) //倒数第2个绑点
                    //{
                    //}
                    else
                    {
                        if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))   //这个判断的意义可以猜猜看
                        {
                            {   //Gamma --R----
                                if (lumr > D_lums[GPN - index, 0])
                                {
                                    if ((!lastdirupR)) { timeout++; }
                                    if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                    lastdirupR = true;
                                }
                                else
                                {
                                    if ((lastdirupR)) { timeout++; }
                                    if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] + rstep;
                                    lastdirupR = false;
                                }
                            }
                            {//Gamma ---G--
                                if (lumg > D_lums[GPN - index, 1])
                                {
                                    if ((!lastdirupG)) { timeout++; }
                                    if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] - gstep;
                                    lastdirupG = true;
                                }
                                else
                                {
                                    if ((lastdirupG)) { timeout++; }
                                    if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] + gstep;
                                    lastdirupG = false;
                                }
                            }
                            {//--Gamma  ---B---
                                if (lumb > D_lums[GPN - index, 2])
                                {
                                    if ((!lastdirupB)) { timeout++; }
                                    if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] - bstep;
                                    lastdirupB = true;
                                }
                                else
                                {
                                    if ((lastdirupB)) { timeout++; }
                                    if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] + bstep;
                                    lastdirupB = false;
                                }
                            }
                            showmsg("rstep: " + rstep + "_gstetp: " + gstep + "_bstep: " + bstep);
                        }   //如果Gamma Value不在目标范围内，此处修正之
                        {//写入Gamma，一共两处都要适配
                            CheckandCorrectGammaValue();
                            //GammaValueFormat_Click(null, null);
                            //显示当前(待)写入的Gamma寄存器值
                            txtGammaValue.Text = GammaValue[GPN - index, 0] + "\r\n" + GammaValue[GPN - index, 1] + "\r\n" + GammaValue[GPN - index, 2] + "\r\n";
                            GammaValueSet((byte)index);
                            Thread.Sleep(20);
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死        
                        } //写入Gamma，一共两处都要适配
                    }
                    if (!STOPAutoGammaFlag)
                        T17.Enabled = true;
                    else return;
                }
            }
            TimTest.Stop();//停止计时
        }
        private void btnVTStop_Click(object sender, EventArgs e)
        {
            T7.Enabled = false;
            STOPAutoGammaFlag = true;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            TimTest.Stop();//停止计时
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            btnCalculateRM692G3.PerformClick();
        }
        private void btnWriteGamma_Click(object sender, EventArgs e)   //检查GammaValue 并且重新转换成指定格式后写入DDIC
        {
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱 ,并刷新表格数据              
            //GammaValueFormat_Click(null, null);  //Gamma 值与实际地址进行转换 
            for (byte i = 0; i < Point_RM692G3.Length; i++)
            {
                GammaValueSet((byte)(i + 1)); //GammaValue 转换成特定格式后再通过此函数写入DDIC
            }
        }
        uint GammaValueMax = 0xFFF - 1;
        private void CheckandCorrectGammaValue()   //检查GammaValue 是否按照大小排列
        {
            byte i; GPN = (byte)Point_RM692G3.Length; // 获取Gamma绑点数量
            GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] & 0xFff;
            GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] & 0xFff;
            GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] & 0xFff;
            if (GammaValue[GPN - 1, 0] > GammaValueMax)
            {
                GammaValue[GPN - 1, 0] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 1] > GammaValueMax)
            {
                GammaValue[GPN - 1, 1] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 2] > GammaValueMax)
            {
                GammaValue[GPN - 1, 2] = GammaValueMax - 16;
            }  //确保GammaValue不要超过DDIC 中Gamma寄存能接受的最大值

            for (i = (byte)(GPN - 1); i > 0; i--)    //低灰阶GammaValue如果大于高灰阶GammaValue则强制变小
            {
                if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                {
                    GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                {
                    GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                {
                    GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                    //GammaValueFormat_Click(null, null);
                }
            }
            GammaValue[0, 0] = 0; GammaValue[0, 1] = 0; GammaValue[0, 2] = 0;
            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.GammaReg_dataGridView.Rows.Clear();
                for (i = 0; i < GPN; i++)
                {
                    DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                }
            }
        }
        private void btnGammaValueUpdate_Click(object sender, EventArgs e)      //刷新UI上表格内的Gamma数据
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GammaValue[i, 0] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GammaValue[i, 1] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GammaValue[i, 2] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");                
                showmsg("Gamma数据更新OK！");
                btnWriteGamma.PerformClick();
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }
        private void numStep_ValueChanged(object sender, EventArgs e)   //手动调整AutoGamma调节步长以在初次调整Gamma是提升速度
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }
        private void chkRM692G3dircshow_CheckedChanged(object sender, EventArgs e)     //Gamma保存时辅助选项 1
        {
            //if (chkRM692G3dircshow.Checked)
            //    chkGammaFormatForRM692G3.Checked = false;
        }
        private void chkGammaFormatForRM692G3_CheckedChanged(object sender, EventArgs e)   ////Gamma保存时辅助选项 2
        {
            //  if (chkGammaFormatForRM692G3.Checked)
            //    chkRM692G3dircshow.Checked = false;
        }
        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        System.DateTime TimeNowT = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        TimeSpan TimeCountT = new TimeSpan();
        Single[,] Gammadbv2Arr = new Single[1, 1];
        byte TotalGammaNum;
        private void txt51Dbv_TextChanged(object sender, EventArgs e)
        {
            string Gammadbv;
            string[] GammadbvGroup = new string[5];
            TotalGammaNum = (byte)txt51Dbv.Lines.Length;
            for (int i = 0; i < TotalGammaNum; i++)
            {
                if (txt51Dbv.Lines[i] == "")
                {
                    TotalGammaNum = (byte)i;
                    break;
                }
            }
            GammadbvGroup = new string[TotalGammaNum];
            Gammadbv2Arr = new Single[TotalGammaNum, 3];
            for (int i = 0; i < TotalGammaNum; i++)
            {
                // GammadbvGroup[i] = txt51Dbv.Lines[i];
                Gammadbv = txt51Dbv.Lines[i]; //GammadbvGroup[i];
                Gammadbv = Gammadbv.Replace(" ", ""); //去空格
                Gammadbv = Gammadbv.Replace(",", " "); // “;”换成空格
                GammadbvGroup = Gammadbv.Trim().Split(' ');
                if (GammadbvGroup[0] == "")
                { break; }
                else
                {
                    try
                    {
                        //byte.Parse((Convert.ToInt32(strTmp, 16)).ToString());  
                        Gammadbv2Arr[i, 0] = (Convert.ToInt32(GammadbvGroup[0], 16));
                        Gammadbv2Arr[i, 1] = (Convert.ToSingle(GammadbvGroup[1])); //  Convert.float(GammadbvGroup[1]);
                        Gammadbv2Arr[i, 2] = (Convert.ToSingle(GammadbvGroup[2]));
                    }
                    catch (FormatException ee)
                    { Console.WriteLine(ee.Message); }
                }
            }
            showmsg((TotalGammaNum) + "条Gamma待调试");
        }
        bool GammatuningOKFlag = false;
        uint[,,] GammaValx = new uint[15, 33, 3];  //提前预定义GammaValue存储区，防止被意外覆盖
                                                   //预定义15条Gamma，25个绑点，R/G/B3个值
                                                   //GammaValx[0]

        private void GammavalMove(int movedir, int n, uint[,,] a_GroupGammaVal, uint[,] b_GammaVal)
        {
            if (movedir == 0)
            {
                for (int inx = 0; inx < GPN; inx++)
                {
                    b_GammaVal[inx, 0] = a_GroupGammaVal[n, inx, 0];
                    b_GammaVal[inx, 1] = a_GroupGammaVal[n, inx, 1];
                    b_GammaVal[inx, 2] = a_GroupGammaVal[n, inx, 2];
                }
            }
            else
            {
                for (int inx = 0; inx < GPN; inx++)
                {
                    a_GroupGammaVal[n, inx, 0] = b_GammaVal[inx, 0];
                    a_GroupGammaVal[n, inx, 1] = b_GammaVal[inx, 1];
                    a_GroupGammaVal[n, inx, 2] = b_GammaVal[inx, 2];
                }
            }
        }
        byte gammaindex = 0;
        private void btnGroupGammaTune_Click(object sender, EventArgs e)
        {
            txtGammaNode_TextChanged(null, null);//获取Gamma绑点
            GPN = (byte)Point_RM692G3.Length; // 获取Gamma绑点数量
            TimeNowT = DateTime.Now; //开始计时
            //gm0 = GroGv.GammaValue0;
            txt51Dbv_TextChanged(null, null);//获取待调节Gamma相关信息

            for (int t = 0; t < TotalGammaNum; t++)
            {
                //GammaValue = GroGv.GammaValue0;
                GammatuningOKFlag = false;
                gammaindex = (byte)t;
                txtVT_lum.Text = Gammadbv2Arr[t, 2] + "";
                GammaBandSelect.Text = Gammadbv2Arr[t, 1].ToString();
                GammavalMove(0, t, GammaValx, GammaValue); //多组GammaValue保存缓冲区搬出指定低t条Gamma至GammaValue
                btnCalGammaValue_Click(null, null);  //计算各绑点Gamma值，并显示GammaValue缓存值
                //btnGammaValueUpdate_Click(null,null);--------------------------
                if (t == 0)
                {

                }//60Hz  配置电压
                else if (t == 5)
                {

                }//60Hz 配置电压
                Dbv51setting((int)Gammadbv2Arr[t, 0]);  //设定51
                //byte[] tep = new byte[1]; int r51Value;
                //r51Value = (int)Gammadbv2Arr[t, 0];
                //Dbv51setting(r51Value);  //设定51
                Thread.Sleep(200);
                //GammaBandSet((byte)Gammadbv2Arr[t, 1]); //Enter Gamma
                btnEnter_gamma_Click(null,null);
                Thread.Sleep(100);
                btnAutoGammas_Click(null, null);
                //while (!GammatuningOKFlag) Application.DoEvents();//重点，必须加上，否则父子窗体都假死;
                if (chkSaveGammavalue.Checked)
                {
                    btnSaveGamma.PerformClick();
                    //btnSaveGamma_Click(btnSaveGamma,null);
                    //Application.DoEvents();//重点，必须加上，否则父子窗体都假死;
                }
                GammavalMove(1, t, GammaValx, GammaValue); //更新多组GammaValue保存缓冲区的第t条Gamma
                showmsg("第" + (t + 1) + "条Gamma调试完成");
                Console.WriteLine("第" + (t + 1) + "条Gamma调试完成");
                TimeCountT = DateTime.Now - TimeNowT;
                showmsg(string.Format("{0:00}:{1:00}:{2:00}", TimeCountT.Hours, TimeCountT.Minutes, TimeCountT.Seconds));
                System.Media.SystemSounds.Beep.Play();
                //System.Media.SystemSounds.Hand.Play();
            }
            showmsg("\r\n---多条Gamma调试完成---\r\n");
            TimeCountT = DateTime.Now - TimeNowT;
            showmsg(string.Format("{0:00}:{1:00}:{2:00}", TimeCountT.Hours, TimeCountT.Minutes, TimeCountT.Seconds));
            System.Media.SystemSounds.Beep.Play();
            Thread.Sleep(2000);
            System.Media.SystemSounds.Hand.Play();
        }
        private void Dbv51setting(int value)
        {
            byte v51h, v51l;
            v51h = Convert.ToByte(value >> 8);
            v51l = Convert.ToByte(value & 0xff);
            byte[] tepArr = new byte[] {
            2,0xfe,00,
            3,0x51,v51h,v51l
            };
            frmMain.frmain.comPort.Write(GetCRCArray(tepArr, 4), 0, tepArr.Length + 6);//循环部分，每段数据结尾  
            Thread.Sleep(20);
            Application.DoEvents();//重点，必须加上，否则父子窗体都假死
        }
        string[] nodeGray = new string[36];
        //private byte ActualUseNodeNum;
        private void txtGammaNode_TextChanged(object sender, EventArgs e)
        {
            //byte ActualUseNodeNum;
            //string Graylv;
            //Graylv = txtGammaNode.Text;
            //Graylv = Graylv.Replace(" ", ""); //去空格
            //Graylv = Graylv.Replace(",", " "); // “;”换成空格
            //nodeGray = Graylv.Trim().Split(' ');
            //// R66462_Point
            //ActualUseNodeNum = (byte)nodeGray.Length;
            ////labGammaPoint.Text = "当前绑点数量：" + ActualUseNodeNum;
            //Point_RM692G3 = new int[ActualUseNodeNum];
            //try
            //{
            //    for (byte i = 0; i < ActualUseNodeNum; i++)
            //    {
            //        Point_RM692G3[i] = Convert.ToByte(nodeGray[i]);
            //    }
            //}
            //catch { }
        }
        string[] Regdata = new string[2];


        public static void RunExe(string exePath, string arguments, out string output, out string error)
        {
            using (Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = exePath;
                process.StartInfo.Arguments = arguments;
                // 必须禁用操作系统外壳程序  
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.Start();
                output = process.StandardOutput.ReadToEnd();
                error = process.StandardError.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }
        }
        private void btnByteRead_Click(object sender, EventArgs e)
        {
            string output;
            string error;
            //写入 FE,00
            RunExe(Application.StartupPath + @"\Resources\adb.exe", @" shell ""echo 0x39 0x01 0x00 0x00 0x00 0x00 0x02 0xfe 0x00 > /d/dri/0/DSI-1/tx_cmd""", out output, out error);
            Console.WriteLine(output + "\n" + error);
            showmsg(output + "\n" + error);
            //读51寄存器，echo 后面的2即是读取2个字节
            RunExe(Application.StartupPath + @"\Resources\adb.exe", @" shell ""echo 0x02 0x06 0x01 0x00 0x00 0x00 0x00 0x01 0x51 > /d/dri/0/DSI-1/rx_cmd""", out output, out error);
            //Console.WriteLine(output + "\n" + error);
            //showmsg(output);
            //从RX拿出51寄存器返回的值
            RunExe(Application.StartupPath + @"\Resources\adb.exe", @" shell ""cat /d/dri/0/DSI-1/rx_cmd""", out output, out error);
            Console.WriteLine(output + "\n" + error);
            showmsg(output);
        }
        private uint[,] R_HZ = new uint[30, 17];
        private uint[,] G_HZ = new uint[30, 17];
        private uint[,] B_HZ = new uint[30, 17];

        private void GammaValueXXX2RGB_HZ() //
        {
            for (int mm = 1; mm < 6; mm++)
            {   //60Hz
                for (int nn = 0; nn < 17; nn++)
                {
                    R_HZ[0 + mm, nn] = GammaValx[5 - mm, nn, 0];
                    G_HZ[0 + mm, nn] = GammaValx[5 - mm, nn, 1];
                    B_HZ[0 + mm, nn] = GammaValx[5 - mm, nn, 2];
                }
            }
            for (int mm = 1; mm < 6; mm++)
            { //90Hz
                for (int nn = 0; nn < 17; nn++)
                {
                    R_HZ[10 + mm, nn] = GammaValx[5 - mm + 5, nn, 0];   // 借用120HzGamma
                    G_HZ[10 + mm, nn] = GammaValx[5 - mm + 5, nn, 1];
                    B_HZ[10 + mm, nn] = GammaValx[5 - mm + 5, nn, 2];
                }
            }
            for (int mm = 1; mm < 6; mm++)
            {//120Hz
                for (int nn = 0; nn < 17; nn++)
                {
                    R_HZ[20 + mm, nn] = GammaValx[5 - mm + 5, nn, 0];
                    G_HZ[20 + mm, nn] = GammaValx[5 - mm + 5, nn, 1];
                    B_HZ[20 + mm, nn] = GammaValx[5 - mm + 5, nn, 2];
                }
            }
        }
        private void RM692EX_120HZ_Gamma_Write(object sender, EventArgs e)
        {
            GammaValueXXX2RGB_HZ(); //把GammaValx内多组Gamma值搬入，以方便借用RM692EX_60HZ_Gamma_Write


        }
        private void RM692EX_60HZ_Gamma_Write(object sender, EventArgs e)
        {

            showmsg("RM692EX 60HZ 载入完成!\r\n");
        }

        private void RM692EX_Gamma_OTP(object sender, EventArgs e)
        {

            MessageBox.Show("OTP完成!");
        }
        private void RM692EX_Inter_Gamma_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            try
            {
                TepArr = new byte[] {
                    2,0xfe,0x80,
                    2,0xa0,0,
                    2,0xfe,0x22,
                    2, 0x06, 0x00,
                    4, 0XFF, 0XFF, 0XFF, 15 };  //byte[] TepArr;
                //TepArr[11] = (byte)GammaBand.Value; //设定对应Gamma序号
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾  
                                                                                           //-----------------  Application.DoEvents();
                                                                                           //Thread.Sleep(50);
                                                                                           //Application.DoEvents();
                                                                                           //GammaReadBackFlag = true;
                                                                                           //frmTop.GeneralRegRead(0xb0, 16);
                                                                                           //Application.DoEvents();
                                                                                           //Thread.Sleep(60);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }

        private void GammaBandSet(Byte GammaBand)
        {
            byte[] TepArr;
            try
            {
                TepArr = new byte[] {
                    2,0xFE,0x00,
                    2,0x8a,FrameRate,  ////120Hz
                    2,0xFE,0x22,
                    2,0x5f,0x02,  //Demura OFF
                     ////Add BCEM Code 
                     ////关闭Gamma内插
                    2,0xFE,0X70,
                    2,0x5d,0x9d,
                    2,0X28,0X00, //Disable Gamma int
                    2,0xfe,0x40,
                    2,0xda,0xc0,//Enable Measure mode //17 Point
                    2,0xd7,GammaBand,//byte.Parse(GammaBandSelect.Text),
                    2,0xfe,0x78,
                    2,0xf4,0xc0,
                    2,0xf5,GammaBand,//byte.Parse(GammaBandSelect.Text) ,
                    //2,0xfe,0x50,
                    //4, 0XFF, 0XFF, 0XFF, 15  //添加此延时会导致代码下发失败，原因未知
                };
                //TepArr[11] = (byte)GammaBand.Value; //设定对应Gamma序号
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }
        //Gamma自动载入
        private void Multi_LoadGamma(string path)
        {
            string strtmp = "";
            //读取文本信息
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            string strLine = streamReader.ReadLine();
            //循环读取文本信息
            while (!string.IsNullOrEmpty(strLine))
            {
                strtmp = strtmp + strLine + ",";
                strLine = streamReader.ReadLine(); //循环读取下一行
            }
            fs.Close(); //关闭流
            streamReader.Close();
            string[] arrtmp = strtmp.Split(new Char[] { ',' });
        }

        private void btnLoadMGroupGamma_Click(object sender, EventArgs e)
        {
            txt51Dbv_TextChanged(null, null);//获取待调节Gamma相关信息
            for (byte nn = 0; nn < TotalGammaNum; nn++)
            {
                gammaindex = nn;
                btnSaveGamma_Click(btnLoadGamma, null);
            }
            GPN = GPN = (byte)Point_RM692G3.Length; // 获取Gamma绑点数量
            GammavalMove(0, 0, GammaValx, GammaValue); //把第一组Gamma从GammaValx搬出至GammaValue
        }

        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private byte[] arrbyte_tmp = new byte[250];         //临时保存下位机返回值
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }
        #endregion  //--- Auto Gamma-----
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        byte FrameRate = 0x17;  //120Hz
        private void btnEnter_gamma_Click(object sender, EventArgs e)
        {  
            byte[] TepArr;
            try
            {
                TepArr = new byte[] {
                    2,0xFE,0x70,
                    2,0x71,0,  
                    2,0x72,0x31,  
                };  
                //TepArr[11] = (byte)GammaBand.Value; //设定对应Gamma序号
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }
        private void button_exit_gamma_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            try
            {
                TepArr = new byte[] {
                    2,0xFE,0x40,
                    2,0xda,0x80,   
                    2,0xFE,0x78,
                    2,0xF4,0x80,   
                    2,0xFE,0X70,
                    2,0x28,0x01,
                    2,0X5D,0X1D,                    
                };                
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }

        private void rdoFramRate120Hz_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoFramRate120Hz.Checked)
            {
                FrameRate = 0x17;
            }
            else FrameRate = 0x18;
        }

        private void btnOpenGammaCSV(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Application.StartupPath + @"\l_gamma");            
        }

        private void btn51Write_Click(object sender, EventArgs e)
        {
            string tepstr;
            tepstr=txtCmd3.Text;
            txtCmd3.Text = "FE,00\r\n"+txtWrite51Value.Text;
            Send_Cmd_Click(btnSend3,null);
            txtCmd3.Text = tepstr;
        }
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        {
                            //frmMain.frmain.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        }
                    }
                    break;
                case "btnSend2":
                    {
                        {
                            frmMain.frmain.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        }
                    }
                    break;
                case "btnSend3":
                    {
                        frmMain.frmain.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {

                frmMain.frmain.SendCmd(0);
            }
            else
            {
                frmMain.frmain.SendCmd(4);
            }
            showmsg("命令已下发...\r\n");
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {

        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            //txtCmd1.Clear();
                            //txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion
    }
}